package com.example.demo.controller;

import com.example.demo.Service.IUserService;
import com.example.demo.core.Result;
import com.example.demo.entity.MsUser;
import com.example.demo.entity.params.UserLoginParam;
import com.example.demo.entity.params.UserRegisterParam;
import com.example.demo.util.JWTUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*")
@Api("")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private PasswordEncoder password;

    @PostMapping("/login")
    public Result login(@RequestBody UserLoginParam userLoginParam){
//        MsUser msUser = userService.selectByUsername(userLoginParam.getUsername());
//        if(msUser == null){
//            return Result.error("用户不存在");
//        }
//        if(!userLoginParam.getPassword().equals(msUser.getPassword())){
//            return Result.error("密码错误");
//        }
//        return Result.success(JWTUtil.createToken(msUser));

        return Result.success(userService.createToken(userLoginParam.getUsername(),userLoginParam.getPassword()));
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserRegisterParam userRegisterParam){

        int a = userService.register(userRegisterParam);

        if(a == 0){
            return Result.error();
        }
        return Result.success();
    }

    @GetMapping("/info")
    public Result info(HttpServletRequest request){
       return Result.success(userService.selectById(JWTUtil.getUserId(request.getHeader("Authorization"))));

    }

//    @GetMapping("test")
//    public void test(){
//        System.out.println(password.encode("123"));
//    }
}
